package com.snail.starter.db.config;

import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import com.snail.starter.db.fill.CustomMetaObjectHandler;
import com.snail.starter.db.holder.DynamicTransactionTemplate;
import com.snail.starter.db.id.CustomIdGenerator;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: snail framework
 * @Date: 2023/2/23 下午5:02
 * @Version: 1.0.0
 */
@Configuration
@MapperScan("com.snail.**.mapper")
public class CustomMybatisPlusConfig {

    @Bean
    IdentifierGenerator identifierGenerator() {
        return new CustomIdGenerator();
    }

    @Bean
    CustomMetaObjectHandler metaObjectHandler() {
        return new CustomMetaObjectHandler();
    }

    @Bean
    DynamicTransactionTemplate dynamicTransactionTemplate(){
        return new DynamicTransactionTemplate();
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                return new StringValue(UserContextUtils.get().getTenantId().toString());
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean ignoreTable(String tableName) {
                return false;
            }
        }));
        return interceptor;
    }

}